package com.ys.controller.api.outer;


import com.ys.entity.base.TbFileInfo;
import com.ys.entity.hr.ThrVatApplyDetail;
import com.ys.entity.hr.ThrVatApplyDetailCbb;
import com.ys.entity.storage.*;
import com.ys.entity.sys.TsFilesInfo;
import com.ys.entity.sys.TsUserChange;
import com.ys.enume.base.TbFileInfoEnum;
import com.ys.mapper.base.TbFileInfoMapper;
import com.ys.mapper.hr.ThrVatApplyDetailCbbMapper;
import com.ys.mapper.storage.TccLogisticsComprehensiveMapper;
import com.ys.mapper.storage.TccLogisticsSadFileMapper;
import com.ys.service.storage.FbaInboundApiService;
import com.ys.service.storage.TccFbaBoxUpService;
import com.ys.service.storage.TccLogisticsComprehensiveOrderService;
import com.ys.util.ToolUtil;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/api/outer/apiOuterDemoLzmmFbaTest")
public class ApiOuterDemoLzmFbaTestController {

    private static final Logger logger = LoggerFactory.getLogger(ApiOuterDemoLzmFbaTestController.class);

	@Autowired
	private FbaInboundApiService fbaInboundApiService;


	@Autowired
	private TccFbaBoxUpService tccFbaBoxUpService;

	@Autowired
	private TccLogisticsComprehensiveOrderService tccLogisticsComprehensiveOrderService;

	@Autowired
	private TccLogisticsSadFileMapper tccLogisticsSadFileMapper;


	@Autowired
	private TbFileInfoMapper tbFileInfoMapper;

	@Autowired
	private ThrVatApplyDetailCbbMapper thrVatApplyDetailCbbMapper;

	@Autowired
	private TccLogisticsComprehensiveMapper tccLogisticsComprehensiveMapper;

	@RequestMapping("/test1")
	@ResponseBody
	public R test1(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			TccFbaBoxUp tccFbaBoxUp = new TccFbaBoxUp().setBid("FBAZX-250314-1002").queryFirst();
			TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(tccFbaBoxUp.getBidFbaPlan()).queryFirst();
//			//获取运输选项与交付窗口
//			R apiRes2 = fbaInboundApiService.generateTransportationAndDeliveryWindow(tccFbaBoxUp);
//			if(apiRes2.getCode().equals(R.Code.FAILED.value)){
//				return apiRes2;
//			}

//			logger.info("***********完成：获取运输选项与交付窗口***********");
//			//设置运输选项与交付窗口
//			R apiRes3 = fbaInboundApiService.confirmTransportationAndDeliveryWindow(tccFbaBoxUp);
//			if(apiRes3.getCode().equals(R.Code.FAILED.value)){
//				return apiRes3;
//			}

//			logger.info("***********完成：设置运输选项与交付窗口***********");
//			//TODO 需测试：查询FBA，新增FBA信息
//			//更新FBA
//			R apiResByGetFbaInfo = fbaInboundApiService.reSearchShipments(tccFbaBoxUp.getBid(),tccFbaPlan,tccFbaBoxUp.getPlacementOptionId());
//			if(apiResByGetFbaInfo.getCode().equals(R.Code.FAILED.value)){
//				return apiResByGetFbaInfo;
//			}


			//获取运输选项与交付窗口
			R apiRes2 = fbaInboundApiService.generateTransportationAndDeliveryWindow(tccFbaBoxUp,tccFbaBoxUp.getPlacementOptionId());
			if(apiRes2.getCode().equals(R.Code.FAILED.value)){
				return apiRes2;
			}
			logger.info("***********完成：设置运输选项与交付窗口***********");
//			//设置运输选项与交付窗口
//			R apiRes3 = fbaInboundApiService.confirmTransportationAndDeliveryWindow(tccFbaBoxUp,tccFbaBoxUp.getPlacementOptionId());
//			if(apiRes3.getCode().equals(R.Code.FAILED.value)){
//				return apiRes3;
//			}

//			logger.info("***********完成：查询FBA，新增FBA信息***********");
//			//TODO 需测试：查询fbano，箱子数据，关联FBA和详情
//			R apiResByGetBox = fbaInboundApiService.getListShipmentBoxesResponse(tccFbaPlan);
//			if(apiResByGetBox.getCode().equals(R.Code.FAILED.value)){
//				return apiResByGetBox;
//			}



			R apiRes1 = fbaInboundApiService.confirmDeliveryWindow(tccFbaBoxUp,tccFbaBoxUp.getPlacementOptionId());
			if(apiRes1.getCode().equals(R.Code.FAILED.value)){
				return apiRes1;
			}

			logger.info("***********完成：1***********");
			R apiResByGetBox = fbaInboundApiService.confirmTransportation(tccFbaBoxUp,tccFbaBoxUp.getPlacementOptionId());
			if(apiResByGetBox.getCode().equals(R.Code.FAILED.value)){
				return apiResByGetBox;
			}

			//R res = tccFbaBoxUpService.examine(tccFbaBoxUp.getBidFbaPlan(),0);
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}






	//测试快驿通- API - C88
	@RequestMapping("/test2")
	@ResponseBody
	public R test2(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
//			String bid = "FBAZX-250325-1001";
//			TccFbaBoxUp tccFbaBoxUp = new TccFbaBoxUp().setBid(bid).queryFirst();
//			TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(tccFbaBoxUp.getBidFbaPlan()).queryFirst();

			tccLogisticsComprehensiveOrderService.apiGetC88ByTimerKyt();
//			R apiResByGetFbaInfo = fbaInboundApiService.reSearchShipments(bid,tccFbaPlan,"plf8393dc0-4818-4f24-b003-6c0e8485f9cf");
//			if(apiResByGetFbaInfo.getCode().equals(R.Code.FAILED.value)){
//				return apiResByGetFbaInfo;
//			}
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}


	//测试快驿通- API - 追踪编号
	@RequestMapping("/test3")
	@ResponseBody
	public R test3(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			tccLogisticsComprehensiveOrderService.apiGetTrackNoByTimerKyt();
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}


	//
	@RequestMapping("/test5")
	@ResponseBody
	public R test5(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
//			List<TccLogisticsSadFile> fileList = new TccLogisticsSadFile().queryList();
//
//			for(TccLogisticsSadFile tccLogisticsSadFile:fileList){
//				logger.info("***********开始:"+tccLogisticsSadFile.getId()+"***********");
//				int declareState = 0;
//				TbFileInfo tbFileInfo = new TbFileInfo().setSourceType(TbFileInfoEnum.SourceType.TCC_LogisticsSadFile_AnnexFile.value).setSourceId(tccLogisticsSadFile.getId()).queryFirst();
//				if(tbFileInfo!=null && tbFileInfo.getId()!=null){
//					ThrVatApplyDetailCbb thrVatApplyDetailCbb = new ThrVatApplyDetailCbb().setCbbId(tbFileInfo.getId()).queryFirst();
//					if(thrVatApplyDetailCbb!=null && thrVatApplyDetailCbb.getId()!=null){
//						declareState = 1;
//					}
//				}
//				tccLogisticsSadFile.setDeclareState(declareState);
//				tccLogisticsSadFileMapper.update(tccLogisticsSadFile);
//			}
//			tccLogisticsComprehensiveOrderService.apiGetTrackNoByTimerKyt();

			List<ThrVatApplyDetailCbb> cbbList = new ThrVatApplyDetailCbb().queryList();
			for(ThrVatApplyDetailCbb thrVatApplyDetailCbb:cbbList){
				logger.info("***********开始"+thrVatApplyDetailCbb.getId()+"***********");
				TbFileInfo tbFileInfo = new TbFileInfo()
						.setSourceType(TbFileInfoEnum.SourceType.TCC_LogisticsSadFile_AnnexFile.value)
						.setId(thrVatApplyDetailCbb.getCbbId())
						.queryFirst();
				if(tbFileInfo!=null && tbFileInfo.getSourceId()!=null){
					thrVatApplyDetailCbb.setCbbId(tbFileInfo.getSourceId());
					thrVatApplyDetailCbbMapper.update(thrVatApplyDetailCbb);
				}

			}




			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



	@RequestMapping("/test6")
	@ResponseBody
	public R test6(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");
			List<TccLogisticsComprehensive> infoList = new TccLogisticsComprehensive()
					.queryList();

			for(TccLogisticsComprehensive tccLogisticsComprehensive:infoList){
				TccFbaDeliverItem tccFbaDeliverItem = new TccFbaDeliverItem().setId(tccLogisticsComprehensive.getFbaDeliverItemId()).queryFirst();

				//计算方数
				List<TccFbaBox> tccFbaBoxList = new TccFbaBox()
						.addLeftJoin("TCC_FbaBoxDetail B ON B.BoxId = A.Id")
						.where("B.FbaBoxUpInfoId = "+tccFbaDeliverItem.getFbaBoxUpInfoId())
						.queryList();
				//去重
				Map<String, List<TccFbaBox>> boxListByGroup = tccFbaBoxList.stream().collect(Collectors.groupingBy(e->e.getId().toString()));
				List<TccFbaBox> boxList = new ArrayList<>();
				//遍历，填入去重的信息
				boxListByGroup.forEach((k, v) -> boxList.add(v.get(0)));
				BigDecimal cubeNum = BigDecimal.ZERO;//总方数

				for(TccFbaBox tccFbaBox:boxList){
					cubeNum = cubeNum.add(tccFbaBox.getBoxLong().multiply(tccFbaBox.getBoxWide()).multiply(tccFbaBox.getBoxHigh()));
				}
				cubeNum = cubeNum.divide(new BigDecimal(1000),2,BigDecimal.ROUND_HALF_UP);
				tccLogisticsComprehensive.setCubeNum(cubeNum);
				tccLogisticsComprehensiveMapper.update(tccLogisticsComprehensive);
			}
			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



	@RequestMapping("/test4")
	@ResponseBody
	public R test4(HttpServletRequest request, HttpServletResponse response
	) {
		try {
			logger.info("***********开始***********");

			List<Map<String, Object>> tsFilesInfoList = new TsFilesInfo()
			.setVtype("C88")
			.addLeftJoin("TP_FbaLogsticsOrder B ON B.Bid = A.BidLogsticsOrder")
					.addField("B.CodeLogsticsServer codeLogsticsServer")//物流服务商
					.addField("B.EntryNumber entryNumber")//进口条目编号
					.addField("B.Code wlCode")// 物流订单号
					.addField("B.NameLogsticsWay nameLogsticsWay")// 物流名称

					//发票号
					//申报时间(C88类型专用)
					//申报状态（0未申报、1已申报）
					//申报单号
					.addLeftJoin("TP_FbaLogsticsOrderDetail E ON E.CodeFbaLogsticsOrder = B.Code")
					.addField("E.ShipmentId shipmentId")//FBA编号

					.addLeftJoin("TP_AmazonAddress F ON E.DestinationFulfillmentCenterId = F.DestinationFulfillmentCenterId")
					.addField("F.countryCode countryCode")//国家编码

					.addLeftJoin("TP_AmazonShop D ON D.Guid = B.SellerId")
					.addLeftJoin("TP_AmazonSeller C ON C.id = D.amazonSellerId")
					.addField("C.Vgsbm vgsbm")
					.addField("C.Vgsjc vgsjc")

					.queryMap();

			List<Map<String, Object>> noFbaList = tsFilesInfoList.stream().filter(e->e.get("shipmentId")!=null).collect(Collectors.toList());

			List<Map<String, Object>> groupsByList = ToolUtil.groupsByList(noFbaList, e->e.get("shipmentId").toString());

			for(Map<String, Object> fileItem:groupsByList){

				logger.info("***********开始："+fileItem.get("shipmentId")+"***********");


				TccLogisticsSadFile tccLogisticsSadFile = new TccLogisticsSadFile();

				if(fileItem.get("shipmentId")!=null)tccLogisticsSadFile.setFbaNo(fileItem.get("shipmentId").toString());
				if(fileItem.get("wlCode")!=null)tccLogisticsSadFile.setLogOrderBid(fileItem.get("wlCode").toString());
				if(fileItem.get("shenbaoTime")!=null)tccLogisticsSadFile.setDeclareTime((Date)fileItem.get("shenbaoTime"));
				if(fileItem.get("stateShenbao")!=null)tccLogisticsSadFile.setDeclareState(Integer.parseInt(fileItem.get("stateShenbao").toString()));//申报状态
				if(fileItem.get("vgsbm")!=null)tccLogisticsSadFile.setVgsbm(fileItem.get("vgsbm").toString());
				if(fileItem.get("nameLogsticsWay")!=null)tccLogisticsSadFile.setLogisticsName(fileItem.get("nameLogsticsWay").toString());
				if(fileItem.get("codeLogsticsServer")!=null)tccLogisticsSadFile.setLogisticsService(fileItem.get("codeLogsticsServer").toString());
				if(fileItem.get("countryCode")!=null)tccLogisticsSadFile.setCountryBid(fileItem.get("countryCode").toString());

				ThrVatApplyDetailCbb thrVatApplyDetailCbb = new ThrVatApplyDetailCbb()
						.setCbbId(Long.parseLong(fileItem.get("id").toString()))
						.queryFirst();
				if(thrVatApplyDetailCbb!=null && thrVatApplyDetailCbb.getId()!=null){
					ThrVatApplyDetail thrVatApplyDetail = new ThrVatApplyDetail()
							.setId(thrVatApplyDetailCbb.getVatApplyDetailId())
							.queryFirst();
					if(thrVatApplyDetail!=null && thrVatApplyDetail.getPbid()!=null){
						tccLogisticsSadFile.setDeclareBid(thrVatApplyDetail.getPbid());//申报单号
					}
				}
				tccLogisticsSadFile.setAnnexFile("1个附件");
				tccLogisticsSadFileMapper.insert(tccLogisticsSadFile);

				TbFileInfo tbFileInfo = new TbFileInfo();
				tbFileInfo.setSourceType(TbFileInfoEnum.SourceType.TCC_LogisticsSadFile_AnnexFile.value);
				tbFileInfo.setSourceId(tccLogisticsSadFile.getId());
				tbFileInfo.setSourceCode("annexFile");
				if(fileItem.get("fileName")!=null)tbFileInfo.setPreName(fileItem.get("fileName").toString());
				if(fileItem.get("fileType")!=null)tbFileInfo.setSufName(fileItem.get("fileType").toString());
				if(fileItem.get("fileType")!=null)tbFileInfo.setFileType(fileItem.get("fileType").toString());
				//if(fileItem.get("fileSize")!=null)tbFileInfo.setFileType(fileItem.get("fileType").toString());
				tbFileInfo.setFilePath(fileItem.get("filePath").toString());
				if(fileItem.get("createUser")!=null){
					TsUserChange tsUserChange = new TsUserChange().setUserId(fileItem.get("createUser").toString()).queryFirst();
					if(tsUserChange!=null && tsUserChange.getId()!=null){
						tbFileInfo.setCreateChangeId(tsUserChange.getId());
					}
				}
				tbFileInfoMapper.insert(tbFileInfo);

				if(thrVatApplyDetailCbb!=null && thrVatApplyDetailCbb.getId()!=null){
					thrVatApplyDetailCbb.setCbbId(tbFileInfo.getId());
					thrVatApplyDetailCbbMapper.update(thrVatApplyDetailCbb);
				}



			}


//			//修改C88文件附件数量
//			int fileCount


			logger.info("***********完成***********");
			return R.ok();
		}catch (Exception e){
			logger.error("操作失败：",e.getMessage(),e);
			return R.error("操作失败!");
		}
	}



//	{
//
//
//		tccFbaInboundApiLog = TccFbaInboundApiLog.tccFbaInboundApiLog("listTransportationOptions", tccFbaPlan.getId().toString(), tccFbaPlan.getBid(),
//				tccFbaPlan.getInboundPlanId(), JSONArray.toJSONString(listTransportationOptionsResponse), 1);
//	}




}
